<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\ProductAttributePrice;
use app\common\model\Product as ProductModel;
use app\common\model\ProductCategory;
use think\Db;
use think\Log;
use think\Exception;

/**
 * APP端商品管理API
 */
class AppProduct extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['getList','getDetail','getAgricultureList','getAgricultureFlashSales','getAgricultureDetail'];

    /**
     * 获取APP端商品列表 （权益商品、积分商品）
     * @ApiMethod (GET)
     * @ApiParams (name="page", type="int", required=false, description="页码，默认1")
     * @ApiParams (name="limit", type="int", required=false, description="每页数量，默认10")
     * @ApiParams (name="type", type="int", required=false, description="商品类型：1权益商品，2积分商品，3助农商品")
     * @ApiParams (name="category_id", type="int", required=false, description="分类ID")
     * @ApiParams (name="keyword", type="string", required=false, description="搜索关键词")
     * @ApiParams (name="sort", type="string", required=false, description="排序方式：price_asc, price_desc, sales_desc, newest")
     */
    public function getList()
    {
        try {
            // 获取请求参数
            $page = $this->request->param('page', 1, 'intval');
            $limit = $this->request->param('limit', 10, 'intval');
            $type = $this->request->param('type', '', 'trim');
            $categoryId = $this->request->param('category_id', '', 'trim');
            $keyword = $this->request->param('keyword', '', 'trim');
            $sort = $this->request->param('sort', 'newest', 'trim');
            $priceRange = $this->request->param('price_range', '', 'trim'); // 价格区间筛选

            // 构建查询条件
            $where = [
                'product.audit_status' => 1,  // 只显示审核通过的商品
                'product.shelf_status' => 1   // 只显示上架的商品
            ];

            // 根据分类ID筛选
            if ($categoryId !== '') {
                $where['product.category_id'] = $categoryId;
            }

            // 构建基础查询条件
            $baseQuery = Db::name('product')
                ->alias('product')
                ->where($where);

            // 关键词搜索
            if (!empty($keyword)) {
                $baseQuery->where('product.name', 'like', '%' . $keyword . '%');
            }

            // 根据商品类型添加额外的筛选条件
            $needJoinAttr = false;
            if ($type !== '') {
                // 指定了商品类型，需要关联属性价格表进行筛选
                $baseQuery->join('product_attribute_price attr', 'product.id = attr.product_id', 'INNER')
                    ->where('attr.attribute_type', $type);
                $needJoinAttr = true;
            }

            // 价格区间筛选
            if (!empty($priceRange)) {
                $this->applyPriceRangeFilter($baseQuery, $priceRange, $type, $needJoinAttr);
            }

            // 获取总数（使用基础查询）
            $countQuery = clone $baseQuery;
            $total = $countQuery->count('DISTINCT product.id');

            // 构建列表查询
            $listQuery = clone $baseQuery;
            
            // 排序处理和字段选择
            switch ($sort) {
                case 'price_asc':
                    if ($type == 2) {
                        // 积分商品按积分排序，使用MIN避免GROUP BY冲突
                        $listQuery->field('product.id,product.name,product.subtitle,product.category_id,product.main_image,product.market_price,product.stock,product.sales,product.createtime,MIN(attr.points) as min_points')
                            ->group('product.id')
                            ->order('min_points asc');
                    } elseif ($type !== '') {
                        // 其他指定类型商品按属性价格排序，使用MIN避免GROUP BY冲突
                        $listQuery->field('product.id,product.name,product.subtitle,product.category_id,product.main_image,product.market_price,product.stock,product.sales,product.createtime,MIN(attr.price) as min_price')
                            ->group('product.id')
                            ->order('min_price asc');
                    } else {
                        // 未指定类型按商品表价格排序
                        $listQuery->field('product.id,product.name,product.subtitle,product.category_id,product.main_image,product.market_price,product.stock,product.sales,product.createtime')
                            ->order('product.price asc');
                    }
                    break;
                case 'price_desc':
                    if ($type == 2) {
                        // 积分商品按积分排序，使用MAX避免GROUP BY冲突
                        $listQuery->field('product.id,product.name,product.subtitle,product.category_id,product.main_image,product.market_price,product.stock,product.sales,product.createtime,MAX(attr.points) as max_points')
                            ->group('product.id')
                            ->order('max_points desc');
                    } elseif ($type !== '') {
                        // 其他指定类型商品按属性价格排序，使用MAX避免GROUP BY冲突
                        $listQuery->field('product.id,product.name,product.subtitle,product.category_id,product.main_image,product.market_price,product.stock,product.sales,product.createtime,MAX(attr.price) as max_price')
                            ->group('product.id')
                            ->order('max_price desc');
                    } else {
                        // 未指定类型按商品表价格排序
                        $listQuery->field('product.id,product.name,product.subtitle,product.category_id,product.main_image,product.market_price,product.stock,product.sales,product.createtime')
                            ->order('product.price desc');
                    }
                    break;
                case 'sales_desc':
                    $listQuery->field('product.id,product.name,product.subtitle,product.category_id,product.main_image,product.market_price,product.stock,product.sales,product.createtime');
                    // 如果关联了属性表，需要按商品ID分组避免重复
                    if ($needJoinAttr || !empty($priceRange)) {
                        $listQuery->group('product.id');
                    }
                    $listQuery->order('product.sales desc');
                    break;
                case 'newest':
                default:
                    $listQuery->field('product.id,product.name,product.subtitle,product.category_id,product.main_image,product.market_price,product.stock,product.sales,product.createtime');
                    // 如果关联了属性表，需要按商品ID分组避免重复
                    if ($needJoinAttr || !empty($priceRange)) {
                        $listQuery->group('product.id');
                    }
                    $listQuery->order('product.id desc');
                    break;
            }

            // 获取列表数据
            $list = $listQuery->page($page, $limit)->select();

            // 获取分类信息
            if (!empty($list)) {
                $categoryIds = array_unique(array_column($list, 'category_id'));
                $categories = Db::name('product_category')
                    ->where('id', 'in', $categoryIds)
                    ->column('name', 'id');

                // 获取所有商品ID
                $productIds = array_column($list, 'id');

                // 获取所有商品的属性价格信息
                $attributePrices = [];
                if (!empty($productIds)) {
                    $queryAttr = ProductAttributePrice::where('product_id', 'in', $productIds);
                    if ($type !== '') {
                        $queryAttr->where('attribute_type', $type);
                    }
                    $attributePriceList = $queryAttr->select();

                    // 按商品ID和属性类型分组
                    foreach ($attributePriceList as $attr) {
                        $productId = $attr['product_id'];
                        $attrType = $attr['attribute_type'];
                        if (!isset($attributePrices[$productId])) {
                            $attributePrices[$productId] = [];
                        }
                        if (!isset($attributePrices[$productId][$attrType])) {
                            $attributePrices[$productId][$attrType] = [];
                        }
                        $attributePrices[$productId][$attrType][] = $attr;
                    }
                }

                foreach ($list as &$item) {
                    $item['category_name'] = isset($categories[$item['category_id']]) ? $categories[$item['category_id']] : '';
                    $item['createtime_text'] = date('Y-m-d H:i:s', $item['createtime']);

                    // 初始化价格相关字段
                    $item['price'] = 0;
                    $item['points'] = 0;
                    $item['equity_value'] = 0;
                    $item['attribute_prices'] = [];

                    // 如果有对应的属性价格信息
                    if (isset($attributePrices[$item['id']])) {
                        $productAttrPrices = $attributePrices[$item['id']];

                        // 如果指定了类型
                        if ($type !== '') {
                            if (isset($productAttrPrices[$type])) {
                                $attrInfos = $productAttrPrices[$type];
                                $item['attribute_prices'] = $attrInfos;

                                // 设置主要价格字段
                                if ($type == 1) {  // 权益商品
                                    $item['price'] = $attrInfos[0]['price'];
                                    $item['equity_value'] = $attrInfos[0]['price'];
                                } elseif ($type == 2) {  // 积分商品
                                    // 积分商品只使用points字段，不再使用price字段
                                    $item['price'] = 0;
                                    $item['points'] = $attrInfos[0]['points'];
                                } elseif ($type == 3) {  // 助农商品
                                    $item['price'] = $attrInfos[0]['price'];
                                }
                            }
                        } else {
                            // 未指定类型，把数字键改成友好的名字
                            $friendlyPrices = [];
                            $defaultPrice = 0;
                            
                            foreach ($productAttrPrices as $attrType => $attrList) {
                                $keyName = $this->getAttributeTypeKey($attrType);
                                $friendlyPrices[$keyName] = $attrList;
                                
                                // 设置默认价格（优先级：权益商品 > 助农商品 > 积分商品）
                                if ($attrType == 1 && isset($attrList[0]['price'])) {
                                    // 权益商品价格
                                    $defaultPrice = $attrList[0]['price'];
                                    $item['equity_value'] = $attrList[0]['price'];
                                } elseif ($attrType == 3 && isset($attrList[0]['price']) && $defaultPrice == 0) {
                                    // 助农商品价格（如果没有权益商品）
                                    $defaultPrice = $attrList[0]['price'];
                                } elseif ($attrType == 2 && isset($attrList[0]['points']) && $defaultPrice == 0) {
                                    // 积分商品（如果没有其他类型）
                                    $defaultPrice = 0; // 积分商品价格设为0
                                    $item['points'] = $attrList[0]['points'];
                                }
                            }
                            
                            $item['price'] = $defaultPrice;
                            $item['attribute_prices'] = $friendlyPrices;
                        }
                    }
                }
            }

            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => [
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit,
                    'list' => $list
                ]
            ]);

        } catch (\Exception $e) {
            Log::error('获取APP商品列表失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }

    /**
     * 获取商品详情
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, description="商品ID")
     */
    public function getDetail()
    {
        try {
            $productId = $this->request->param('id');
            if (!$productId) {
                return json(['code' => 0, 'msg' => '商品ID不能为空', 'data' => []]);
            }
            $requestType = $this->request->param('type');
            if(!$requestType){
                return json(['code' => 0, 'msg' => '商品类型不能为空', 'data' => []]);
            }


            // 查询商品基本信息
            $product = Db::name('product')
                ->where('id', $productId)
                ->where('audit_status', 1)    // 只显示审核通过的商品
                ->where('shelf_status', 1)    // 只显示上架的商品
                ->find();

            if (!$product) {
                return json(['code' => 0, 'msg' => '商品不存在或已下架', 'data' => []]);
            }

            // 查询分类信息
            $category = null;
            if ($product['category_id']) {
                $category = Db::name('product_category')
                    ->where('id', $product['category_id'])
                    ->field('id,name')
                    ->find();
            }

            // 查询商品图片
            $images = Db::name('product_image')
                ->where('product_id', $productId)
                ->field('id,product_id,image_url,image_type,sort')
                ->order('sort asc')
                ->select();

            // 分离轮播图和详情图
            $carouselImages = [];
            $detailImages = [];
            if ($images) {
                foreach ($images as $image) {
                    if ($image['image_type'] == 1) {
                        $carouselImages[] = $image['image_url'];
                    } elseif ($image['image_type'] == 2) {
                        $detailImages[] = $image['image_url'];
                    }
                }
            }

            // 如果没有轮播图，使用主图
            if (empty($carouselImages) && !empty($product['main_image'])) {
                $carouselImages[] = $product['main_image'];
            }

            // 查询商品SKU信息
            $skus = Db::name('product_sku')
                ->where('product_id', $productId)
                ->field('id,sku_code,sku_name,spec_value_ids,price,original_price,stock,weight,status')
                ->order('id asc')
                ->select();

            // 查询商品属性价格信息
            $attributePrices = Db::name('product_attribute_price')
                ->where('attribute_type', $requestType)
                ->where('product_id', $productId)
                ->field('attribute_type,price,points,is_default,sku_id')
                ->select();
            
            // 调试信息：输出属性价格数据
            Log::info('商品ID ' . $productId . ' 的属性价格数据：' . json_encode($attributePrices ?: []));
            Log::info('商品ID ' . $productId . ' 的SKU数据：' . json_encode($skus ?: []));

            // 根据请求的type构建商品价格信息
            $productType = [];
            $pricesBySku = []; // SKU价格映射

            if ($attributePrices) {
                // 建立SKU价格映射
                foreach ($attributePrices as $attr) {
                    if (!empty($attr['sku_id'])) {
                        $pricesBySku[$attr['sku_id']] = $attr;
                    }
                }

                // 构建请求类型的数据
                $typeData = [
                    'type' => $requestType,
                    'is_default' => $attributePrices[0]['is_default'] ?? false,
                    'skus' => []
                ];

                switch ($requestType) {
                    case 1: // 权益商品
                        $typeData['name'] = '权益商品';
                        $typeData['price'] = $attributePrices[0]['price'] ?? 0;
                        break;
                    case 2: // 积分商品
                        $typeData['name'] = '积分商品';
                        $typeData['points'] = $attributePrices[0]['points'] ?? 0;
                        break;
                    case 3: // 助农商品
                        $typeData['name'] = '助农商品';
                        $typeData['price'] = $attributePrices[0]['price'] ?? 0;
                        break;
                    default:
                        $typeData['name'] = '普通商品';
                        $typeData['price'] = $attributePrices[0]['price'] ?? 0;
                        break;
                }

                // 处理SKU信息
                if ($skus) {
                    foreach ($skus as $sku) {
                        $skuPrice = $sku['price']; // 默认使用SKU表中的价格
                        
                        // 查找该SKU对应的属性价格记录
                        if (isset($pricesBySku[$sku['id']])) {
                            $matchedAttrPrice = $pricesBySku[$sku['id']];
                            if ($requestType == 2) {
                                $skuPrice = $matchedAttrPrice['points']; // 积分商品使用points字段
                            } else {
                                $skuPrice = $matchedAttrPrice['price']; // 其他类型使用price字段
                            }
                        } else {
                            // 如果没有SKU特定价格，查找通用价格（sku_id为空的记录）
                            foreach ($attributePrices as $attr) {
                                if (empty($attr['sku_id']) || $attr['sku_id'] == 0) {
                                    if ($requestType == 2) {
                                        $skuPrice = $attr['points'];
                                    } else {
                                        $skuPrice = $attr['price'];
                                    }
                                    break;
                                }
                            }
                        }
                        
                        $typeData['skus'][] = [
                            'id' => $sku['id'],
                            'sku_code' => $sku['sku_code'],
                            'sku_name' => $sku['sku_name'],
                            'spec_value_ids' => $sku['spec_value_ids'],
                            'price' => $skuPrice,
                            'original_price' => $sku['original_price'],
                            'stock' => $sku['stock'],
                            'weight' => $sku['weight'],
                            'status' => $sku['status']
                        ];
                    }
                }

                $productType = $typeData;
            } else {
                // 如果没有找到对应类型的属性价格，返回默认商品信息
                $productType = [
                    'type' => $requestType,
                    'name' => $this->getAttributeTypeName($requestType),
                    'price' => $product['price'],
                    'is_default' => false,
                    'skus' => []
                ];

                // 添加SKU信息
                if ($skus) {
                    foreach ($skus as $sku) {
                        $productType['skus'][] = [
                            'id' => $sku['id'],
                            'sku_code' => $sku['sku_code'],
                            'sku_name' => $sku['sku_name'],
                            'spec_value_ids' => $sku['spec_value_ids'],
                            'price' => $sku['price'],
                            'original_price' => $sku['original_price'],
                            'stock' => $sku['stock'],
                            'weight' => $sku['weight'],
                            'status' => $sku['status']
                        ];
                    }
                }
            }

            // 构建返回数据
            $result = [
                'id' => $product['id'],
                'name' => $product['name'],
                'subtitle' => $product['subtitle'] ?? '',
                'category_id' => $product['category_id'],
                'category_name' => $category ? $category['name'] : '',
                'main_image' => $product['main_image'],
                'carousel_images' => $carouselImages,
                'detail_images' => $detailImages,
                'description' => $product['description'] ?? '',
                'product_type' => $productType,
                'stock' => $product['stock'],
                'sales' => $product['sales'] ?? 0,
                'createtime' => $product['createtime']
            ];

            return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);

        } catch (\Exception $e) {
            Log::error('获取APP商品详情失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }

    /**
     * 获取商品分类列表
     * @ApiMethod (GET)
     */
    public function getCategories()
    {
        try {
            // 获取所有启用的分类
            $categories = Db::name('product_category')
                ->where('status', 1)
                ->field('id,parent_id,name,sort')
                ->order('parent_id asc, sort asc, id asc')
                ->select();

            // 构建树形结构
            $tree = $this->buildCategoryTree($categories);

            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => $tree
            ]);

        } catch (\Exception $e) {
            Log::error('获取商品分类失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }

    /**
     * 构建分类树形结构
     */
    private function buildCategoryTree($categories, $parentId = 0)
    {
        $tree = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                $children = $this->buildCategoryTree($categories, $category['id']);
                if (!empty($children)) {
                    $category['children'] = $children;
                }
                $tree[] = $category;
            }
        }
        return $tree;
    }

    /**
     * 获取属性类型名称
     * @param int $type 属性类型
     * @return string
     */
    private function getAttributeTypeName($type)
    {
        $typeNames = [
            1 => '权益商品',
            2 => '积分商品',
            3 => '助农商品'
        ];
        return isset($typeNames[$type]) ? $typeNames[$type] : '未知类型';
    }

    /**
     * 获取属性类型的友好键名
     * @param int $type 属性类型
     * @return string
     */
    private function getAttributeTypeKey($type)
    {
        $typeKeys = [
            1 => 'equity',    // 权益商品
            2 => 'points',    // 积分商品
            3 => 'normal'     // 助农商品
        ];
        return isset($typeKeys[$type]) ? $typeKeys[$type] : 'unknown';
    }

    /**
     * 应用价格区间筛选
     * @param object $query 查询对象
     * @param string $priceRange 价格区间
     * @param string $type 商品类型
     * @param bool $needJoinAttr 是否已经关联了属性表
     */
    private function applyPriceRangeFilter($query, $priceRange, $type, $needJoinAttr)
    {
        // 解析价格区间
        $minPrice = null;
        $maxPrice = null;
        
        if (strpos($priceRange, '-') !== false) {
            // 解析区间格式：如 "100-500", "0-50"
            $parts = explode('-', $priceRange);
            if (count($parts) == 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
                $minPrice = floatval($parts[0]);
                $maxPrice = floatval($parts[1]);
            }
        } elseif (strpos($priceRange, '+') !== false) {
            // 解析开放区间格式：如 "500+", "150+"
            $minPrice = floatval(str_replace('+', '', $priceRange));
            $maxPrice = null;
        } elseif (is_numeric($priceRange)) {
            // 单个数值，表示最小价格：如 "100"
            $minPrice = floatval($priceRange);
            $maxPrice = null;
        }
        
        // 如果解析失败，直接返回
        if ($minPrice === null) {
            return;
        }

        // 根据商品类型选择筛选字段
        if ($type == 2) {
            // 积分商品按积分筛选
            if (!$needJoinAttr) {
                // 如果还没有关联属性表，需要关联
                $query->join('product_attribute_price attr', 'product.id = attr.product_id', 'INNER')
                    ->where('attr.attribute_type', 2);
            }
            
            if ($maxPrice !== null) {
                $query->where('attr.points', 'between', [$minPrice, $maxPrice]);
            } else {
                $query->where('attr.points', '>=', $minPrice);
            }
        } else {
            // 权益商品和助农商品按价格筛选
            if ($type !== '' && $type != 2) {
                // 指定了非积分商品类型，需要关联属性表
                if (!$needJoinAttr) {
                    $query->join('product_attribute_price attr', 'product.id = attr.product_id', 'INNER')
                        ->where('attr.attribute_type', $type);
                }
                
                if ($maxPrice !== null) {
                    $query->where('attr.price', 'between', [$minPrice, $maxPrice]);
                } else {
                    $query->where('attr.price', '>=', $minPrice);
                }
            } else {
                // 未指定类型或混合类型，使用商品表的价格字段
                if ($maxPrice !== null) {
                    $query->where('product.price', 'between', [$minPrice, $maxPrice]);
                } else {
                    $query->where('product.price', '>=', $minPrice);
                }
            }
        }
    }

    /**
     * 获取助农商品列表
     */
    public function getAgricultureList()
    {
        $page = input('page', 1, 'intval');
        $limit = input('limit', 10, 'intval');
        $flash_sale_id = input('flash_sale_id', 0, 'intval');

        // 获取抢购场次
        if ($flash_sale_id > 0) {
            $flashSale = Db::name('agriculture_flash_sale')->where('id', $flash_sale_id)->find();
        } else {
            $now = time();
            $flashSale = Db::name('agriculture_flash_sale')
                ->where('start_time', '<=', $now)
                ->where('end_time', '>=', $now)
                ->where('status', 1)
                ->order('id desc')
                ->find();
        }

        if (!$flashSale) {
            return json(['code' => 0, 'msg' => '暂无抢购场次']);
        }

        // 先获取抢购商品的商品ID列表（去重）
        $productIds = Db::name('agriculture_flash_sale_product')
            ->where('flash_sale_id', $flashSale['id'])
            ->group('product_id')
            ->column('product_id');

        if (empty($productIds)) {
            return json(['code' => 1,'msg' => '获取成功','data' => []]);
        }

        // 直接查询有效的商品数据（确保有抢购信息的商品）
        $validProducts = Db::name('product p')
            ->join('agriculture_flash_sale_product afsp', 'p.id = afsp.product_id')
            ->where('afsp.flash_sale_id', $flashSale['id'])
            ->where('p.audit_status', 1)
            ->where('p.shelf_status', 1)
            ->group('p.id')
            ->field('p.id, p.name, p.main_image, MIN(afsp.flash_price) as min_price')
            ->order('p.id desc')
            ->select();

        $total = count($validProducts);
        
        // 手动分页
        $offset = ($page - 1) * $limit;
        $products = array_slice($validProducts, $offset, $limit);

        // 获取当前页商品的抢购信息
        $currentPageProductIds = array_column($products, 'id');
        $flashProducts = Db::name('agriculture_flash_sale_product')
            ->where('flash_sale_id', $flashSale['id'])
            ->where('product_id', 'in', $currentPageProductIds)
            ->order('flash_price asc')
            ->select();

        // 按商品ID分组，每个商品只取最低价格的规格
        $flashProductMap = [];
        foreach ($flashProducts as $flashProduct) {
            $productId = $flashProduct['product_id'];
            if (!isset($flashProductMap[$productId])) {
                $flashProductMap[$productId] = $flashProduct;
            }
        }

        // 组装最终数据
        $list = [];
        foreach ($products as $product) {
            $flashProduct = isset($flashProductMap[$product['id']]) ? $flashProductMap[$product['id']] : null;
            if ($flashProduct) {
                $list[] = [
                    'id' => $product['id'],
                    'name' => $product['name'],
                    'main_image' => $product['main_image'],
                    'flash_price' => $flashProduct['flash_price'],
                    'original_price' => $flashProduct['original_price'],
                    'stock' => $flashProduct['stock'],
                    'sales' => $flashProduct['sales']
                ];
            }
        }

        return json([
            'code' => 1,
            'msg' => '获取成功',
            'data' => [
                'list' => $list,
                'total' => $total,
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }

    /**
     * 获取助农商品详情（包含抢购信息）
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, description="商品ID")
     * @ApiParams (name="flash_sale_id", type="integer", required=false, description="抢购场次ID，不传则获取当前进行中的场次")
     */
    public function getAgricultureDetail()
    {
        try {
            $productId = $this->request->param('id');
            if (!$productId) {
                return json(['code' => 0, 'msg' => '商品ID不能为空', 'data' => []]);
            }

            $flashSaleId = $this->request->param('flash_sale_id', '', 'trim');
            if (!$flashSaleId) {
                return json(['code' => 0, 'msg' => '场次不能为空', 'data' => []]);

            }

            // 验证指定的抢购场次是否存在
            $flashSale = Db::name('agriculture_flash_sale')
                ->where('id', $flashSaleId)
                ->find();
                
            if (!$flashSale) {
                return json(['code' => 0, 'msg' => '指定的抢购场次不存在', 'data' => []]);
            }
            
            // 查询商品基本信息
            $product = Db::name('product')
                ->where('id', $productId)
                ->where('audit_status', 1)    // 只显示审核通过的商品
                ->where('shelf_status', 1)    // 只显示上架的商品
                ->find();

            if (!$product) {
                return json(['code' => 0, 'msg' => '商品不存在或已下架', 'data' => []]);
            }

            // 查询抢购商品信息
            $flashProducts = Db::name('agriculture_flash_sale_product')
                ->where('flash_sale_id', $flashSaleId)
                ->where('product_id', $productId)
                ->select();
            
            if (!$flashProducts) {
                return json(['code' => 0, 'msg' => '该商品不在当前抢购活动中', 'data' => []]);
            }
            
            // 将抢购商品信息按SKU ID分组
            $flashProductMap = [];
            foreach ($flashProducts as $flashProduct) {
                $flashProductMap[$flashProduct['product_sku_id']] = $flashProduct;
            }

            // 查询分类信息
            $category = null;
            if ($product['category_id']) {
                $category = Db::name('product_category')
                    ->where('id', $product['category_id'])
                    ->field('id,name')
                    ->find();
            }
            
            // 查询商品图片
            $images = Db::name('product_image')
                ->where('product_id', $productId)
                ->field('id,product_id,image_url,image_type,sort')
                ->order('sort asc')
                ->select();
            
            // 分离轮播图和详情图
            $carouselImages = [];
            $detailImages = [];
            if ($images) {
                foreach ($images as $image) {
                    if ($image['image_type'] == 1) {
                        $carouselImages[] = $image['image_url'];
                    } elseif ($image['image_type'] == 2) {
                        $detailImages[] = $image['image_url'];
                    }
                }
            }

            // 如果没有轮播图，使用主图
            if (empty($carouselImages) && !empty($product['main_image'])) {
                $carouselImages[] = $product['main_image'];
            }

            // 查询商品SKU信息
            $skus = Db::name('product_sku')
                ->where('product_id', $productId)
                ->field('id,sku_code,sku_name,spec_value_ids,price,original_price,stock,weight,status')
                ->order('id asc')
                ->select();
            
            // 处理SKU信息，应用抢购价格
            $flashSkus = [];
            if ($skus) {
                foreach ($skus as $sku) {
                    // 查找对应的抢购信息
                    $flashProduct = isset($flashProductMap[$sku['id']]) ? $flashProductMap[$sku['id']] : null;
                    
                    if ($flashProduct) {
                        // 如果该SKU参与抢购，使用抢购价格
                        $flashSkus[] = [
                            'id' => $sku['id'],
                            'sku_code' => $sku['sku_code'],
                            'sku_name' => $sku['sku_name'],
                            'spec_value_ids' => $sku['spec_value_ids'],
                            'original_price' => $sku['original_price'], // 使用SKU原价
                            'flash_price' => $flashProduct['flash_price'], // 抢购价
                            'stock' => min($sku['stock'], $flashProduct['stock']), // 取较小值作为可购买库存
                            'weight' => $sku['weight'],
                            'status' => $sku['status']
                        ];
                    } else {
                        // 如果该SKU不参与抢购，使用原价
                        $flashSkus[] = [
                            'id' => $sku['id'],
                            'sku_code' => $sku['sku_code'],
                            'sku_name' => $sku['sku_name'],
                            'spec_value_ids' => $sku['spec_value_ids'],
                            'original_price' => $sku['original_price'],
                            'flash_price' => $sku['price'], // 没有抢购价，使用原价
                            'stock' => $sku['stock'],
                            'weight' => $sku['weight'],
                            'status' => $sku['status']
                        ];
                    }
                }
            }

            // 计算抢购进度和状态（基于所有参与抢购的SKU）
            $totalStock = 0;
            $totalSales = 0;
            foreach ($flashProducts as $flashProduct) {
                $totalStock += $flashProduct['stock'];
                $totalSales += $flashProduct['sales'];
            }
            
            $progress = ($totalStock + $totalSales) > 0 ? 
                round(($totalSales / ($totalSales + $totalStock)) * 100, 2) : 100;

            $currentTime = time();
            if ($currentTime < $flashSale['start_time']) {
                $flashStatus = 'upcoming'; // 即将开始
                $flashStatusText = '即将开始';
            } elseif ($currentTime >= $flashSale['start_time'] && $currentTime <= $flashSale['end_time']) {
                if ($totalStock > 0) {
                    $flashStatus = 'ongoing'; // 抢购中
                    $flashStatusText = '抢购中';
                } else {
                    $flashStatus = 'sold_out'; // 已售罄
                    $flashStatusText = '已售罄';
                }
            } else {
                $flashStatus = 'ended'; // 已结束
                $flashStatusText = '已结束';
            }

            // 计算价格范围
            $flashPrices = array_column($flashProducts, 'flash_price');
            $minFlashPrice = min($flashPrices);
            $maxFlashPrice = max($flashPrices);
            
            // 获取限购数量（取第一个抢购商品的限购数量，通常同一商品的限购数量相同）
            $limitNum = $flashProducts[0]['limit_num'];

            // 构建返回数据
            $result = [
                'id' => $product['id'],
                'name' => $product['name'],
                'subtitle' => $product['subtitle'] ?? '',
                'category_id' => $product['category_id'],
                'category_name' => $category ? $category['name'] : '',
                'main_image' => $product['main_image'],
                'carousel_images' => $carouselImages,
                'detail_images' => $detailImages,
                'description' => $product['description'] ?? '',
                'stock' => $product['stock'],
                'sales' => $product['sales'] ?? 0,
                'createtime' => $product['createtime'],
                'skus' => $flashSkus
            ];

            return json(['code' => 1, 'msg' => '获取成功', 'data' => $result]);

        } catch (\Exception $e) {
            Log::error('获取助农商品详情失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }

    /**
     * 获取助农抢购场次列表
     * @ApiMethod (GET)
     * @ApiParams (name="status", type="string", required=false, description="状态筛选：upcoming(即将开始), ongoing(进行中), ended(已结束)")
     */
    public function getAgricultureFlashSales()
    {
        try {
            $status = $this->request->param('status', '', 'trim');
            $currentTime = time();

            // 构建查询条件
            $where = ['status' => 1];

            $query = Db::name('agriculture_flash_sale')->field('id,start_time,end_time')->where($where);

            // 根据状态筛选
            if ($status) {
                switch ($status) {
                    case 'upcoming':
                        $query->where('start_time', '>', $currentTime);
                        break;
                    case 'ongoing':
                        $query->where('start_time', '<=', $currentTime)
                              ->where('end_time', '>=', $currentTime);
                        break;
                    case 'ended':
                        $query->where('end_time', '<', $currentTime);
                        break;
                }
            }

            $list = $query->order('start_time desc')->select();

            // 处理数据
            foreach ($list as &$item) {
                $item['start_time_text'] = date('Y-m-d H:i:s', $item['start_time']);
                $item['end_time_text'] = date('Y-m-d H:i:s', $item['end_time']);
                
                // 计算状态
                if ($currentTime < $item['start_time']) {
                    $item['current_status'] = 'upcoming';
                    $item['current_status_text'] = '即将开始';
                } elseif ($currentTime >= $item['start_time'] && $currentTime <= $item['end_time']) {
                    $item['current_status'] = 'ongoing';
                    $item['current_status_text'] = '进行中';
                } else {
                    $item['current_status'] = 'ended';
                    $item['current_status_text'] = '已结束';
                }

                // 获取该场次的商品数量
                $item['product_count'] = Db::name('agriculture_flash_sale_product')
                    ->where('flash_sale_id', $item['id'])
                    ->count();
            }

            return json(['code' => 1, 'msg' => '获取成功', 'data' => $list]);

        } catch (\Exception $e) {
            Log::error('获取助农抢购场次列表失败: ' . $e->getMessage());
            return json(['code' => 0, 'msg' => '系统错误，请稍后重试', 'data' => []]);
        }
    }

}